package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Async(value = "taskExecutor")
    @Override
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        // 按照文章id 点赞降序 查询热点文章
        log.info("计算热点评论异步方法开始执行 ==> ");
        Query query = Query.query(Criteria.where("entryId").is(entryId)
                .and("flag").is(1)).with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        // 没有热评 热评数量小于5 直接修改热评
        if (apComments == null || apComments.size() < 5){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        // 大于等于5 和热评最后一条相比点赞数，数量高的改为热评，最后一个改为普通评论
        ApComment lastHotApComment = apComments.get(apComments.size() - 1);
        if (apComment.getLikes() > lastHotApComment.getLikes()){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            lastHotApComment.setFlag((short) 0);
            mongoTemplate.save(lastHotApComment);
            log.info("计算热点评论异步方法结束执行 ==> ");
            return;
        }

    }
}
